package chapter2;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author Hang
 * @date 2022/8/9
 * @project AutumnOffer
 * @description 面试题9 用两个栈实现队列
 **/
public class CQueue {
    private static Deque<Integer> instack;
    private static Deque<Integer> outstack;

    public CQueue(){
        instack = new ArrayDeque<>(); // 入栈
        outstack = new ArrayDeque<>(); // 出栈
    }

    public static void appendTail(int value){
        instack.push(value); // 添加到队尾
    }

    public static int deleteHead(){
        if(!outstack.isEmpty()){ // 先判断出栈是否为空，不为空，直接出队
            return outstack.pop();
        }else {
            while (!instack.isEmpty()){
                outstack.push(instack.pop()); // 为空则判断入队是否为空，不为空则迁移
            }
            return outstack.isEmpty()?-1:outstack.pop(); //最后将出队的内容判断，不为空返回栈顶
        }
    }

    public static void main(String[] args) {
        CQueue cQueue = new CQueue();
        cQueue.appendTail(1);
        cQueue.appendTail(2);
        cQueue.appendTail(4);
        cQueue.appendTail(3);
        for (int i = 0; i < 4; i++) {
            System.out.println(cQueue.deleteHead());
        }
    }
}
